package com.altekis.kanbankaze.client;

import com.altekis.kanbankaze.shared.events.RPCCompletedEvent;
import com.altekis.kanbankaze.shared.events.RPCCompletedEventHandler;
import com.altekis.kanbankaze.shared.events.RPCStartedEvent;
import com.altekis.kanbankaze.shared.events.RPCStartedEventHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class BusyIndicatorPresenter {
	interface Display {
		void showIndicator(String text);
		void hideIndicator();
	}

	protected Display display;
	private int activeRPCCount = 0;
	protected final EventBus eventBus;

	@Inject
	public BusyIndicatorPresenter(EventBus eventBus) {
		super();
		this.eventBus = eventBus;
		eventBus.addHandler(RPCCompletedEvent.TYPE, new RPCCompletedEventHandler() {
			@Override
			public void onRPCCompleted(RPCCompletedEvent event) {
				activeRPCCount = activeRPCCount > 0 ? --activeRPCCount : 0;
				if (activeRPCCount <= 0) {
					hideIndicator();
				}
			}
		});
		eventBus.addHandler(RPCStartedEvent.TYPE, new RPCStartedEventHandler() {
			@Override
			public void onRPCStarted(RPCStartedEvent rpcStartedEvent) {
				activeRPCCount++;
				showIndicator("Calling " + activeRPCCount);
			}
		});
	}
	
	void bindDisplay(Display display) {
		this.display = display;
	}

	private void hideIndicator() {
		display.hideIndicator();
	}
	private void showIndicator(String text) {
		display.showIndicator(text);
	}
}